package git.soulbgm.common.filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * @author SoulBGM
 * @version 1.0
 * @date 2019/10/14 15:09
 */
public class UrlPathMatchingFilter extends PermissionsAuthorizationFilter {

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        //请求的url
        String requestUrl = getPathWithinApplication(request);
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            WebUtils.toHttp(response).sendError(401, "未知用户");
            return false;
        }

        boolean permitted = subject.isPermitted(requestUrl);
        if (!permitted) {
            WebUtils.toHttp(response).sendError(403, "未经授权");
            return false;
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        return false;
    }
}
